package ReefStats::Controller::Statistics;

use strict;
use warnings;
use base 'Catalyst::Controller::FormBuilder';
use DateTime;
use constant ALL_DOMAINS => '-- All Domains --';

=head1 NAME

ReefStats::Controller::Statistics - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 index 

=cut

sub index : Private {
    my ( $self, $c ) = @_;

    $c->response->body(
        'Matched ReefStats::Controller::Statistics in Statistics.');
}

sub original : Local {
    my ( $self, $c ) = @_;
}

sub one_day : Local Form {
    my ( $self, $c ) = @_;

    my $form = $self->formbuilder;

    $form->messages( form_select_default => 'XXX' );

    $form->field(
        name    => 'domain',
        options => [
            ALL_DOMAINS,
            map { [ $_->id, $_->domain ] }
              $c->model('Domains')->search( undef, { order_by => 'domain' } )
        ]
    );

    return unless $form->submitted && $form->validate;

    my $maillog = $c->model('Maillog');

    my $domain = $form->param('domain');
    $domain = ($domain
      and $domain ne ALL_DOMAINS) ? $c->model('Domains')->find($domain) : qw{};

    $c->log->info("domain [$domain]");

    my $lower_date = $form->param('day');
    if ( $lower_date =~ /(\d{2})\/(\d{2})\/(\d{4})/ ) {
        $lower_date = DateTime->new(
            year   => $3,
            month  => $1,
            day    => $2,
            hour   => 0,
            minute => 0,
            second => 0,
        );
    }
    else {
        die 'invalid date';
    }

    my $upper_date = DateTime->new(
        year   => $lower_date->year,
        month  => $lower_date->month,
        day    => $lower_date->day,
        hour   => 23,
        minute => 59,
        second => 59,
    );

    my $search_criteria =
      { timestamp => { -between => [ $lower_date, $upper_date ] }, };
    $search_criteria->{domain} = $domain->domain if $domain;

    for my $reason (qw(Virus Blacklist)) {
        $search_criteria->{reason} = $reason;
        $c->stash->{ 'ReasonExt_' . $reason } = $maillog->search(
            {%$search_criteria},
            {
                select => [ 'reasonext', { count => 'reasonext' } ],
                as       => [qw( reasonext reasonext_count )],
                group_by => [qw( reasonext )],
                order_by => 'count(reasonext) desc',
                rows     => 10,
            }
        );
    }

    delete $search_criteria->{reason};

    $c->stash->{ ucfirst $_ } = $maillog->search(
        {%$search_criteria},
        {
            select   => [ $_, { count => $_ } ],
            as       => [ $_, $_ . '_count' ],
            group_by => [$_],
            order_by => "count($_) desc",
            rows     => 10,
        }
    ) for qw(recipient action reason domain);
}

=head1 AUTHOR

Joshua McAdams

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
